﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
using System.Web;
using Job.Logic.Personal;
using Job.Web.Framework;


namespace Job.Logic.Handler
{
    public class GetUserPhoto : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString["personalid"] != null && context.Request.QueryString["personalId"] != string.Empty)
            {
                int personinfoid = Convert.ToInt32( context.Request.QueryString["personalId"]);
                Int32 height = 140;
                Int32 width = 105;
                string extName = context.Request.QueryString["type"];
                if (context.Request.QueryString["W"] != null && context.Request.QueryString["W"] != string.Empty)
                {
                    try
                    {
                        int.TryParse(context.Request.QueryString["W"], out width);
                    }
                    catch { }
                }
                if (context.Request.QueryString["H"] != null && context.Request.QueryString["H"] != string.Empty)
                {
                    try
                    {
                        int.TryParse(context.Request.QueryString["H"], out height);
                    }
                    catch { }
                }

                ProcessStream(context.Response.OutputStream, width, height, personinfoid, extName);

                if (extName.ToUpper().Equals(".GIF"))
                {
                    context.Response.ContentType = "image/gif";
                }
                else
                {
                    context.Response.ContentType = "image/jpeg";
                }
            }

        }

        #endregion

        private void ProcessStream(Stream stream, int width, int height, int personinfoid,string extName)
        {
            Stream imgStream = null;
            Stream zonedStream = null;
            try
            {
                PersonalLogic pl = new PersonalLogic();
                byte[] photo = pl.GetUserPhoto(personinfoid).UserPhoto;
                if (photo != null)
                {
                    imgStream = Functions.ByteArrayToStream(photo);
                    zonedStream = WriteStream(imgStream, width, height, personinfoid,extName);
                    OutputStream(zonedStream, stream);
                }
            }
            catch (Exception ex)
            {
            }

            finally
            {
                //imgStream.Dispose();
                //zonedStream.Dispose();
            }
        }

        private void OutputStream(Stream srcStream, Stream disStream)
        {
            try
            {
                if (disStream.CanWrite && srcStream.CanRead)
                {
                    if (srcStream.CanSeek)
                    {
                        srcStream.Seek(0, SeekOrigin.Begin);
                    }
                    byte[] buffer = new byte[4096];
                    while (true)
                    {
                        int size = srcStream.Read(buffer, 0, buffer.Length);
                        if (size > 0)
                        {
                            disStream.Write(buffer, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //Freeborders.Utility.RSExceptionManager.Log("FileCacheUtility WriteStream Error:", e);
            }
        }

        private Stream WriteStream(Stream stream, int width, int height, int personinfoid,string extName)
        {
            Bitmap _OriginalImage = new Bitmap(stream);
            Bitmap tempImage = null;
            Stream oZonedStream = new MemoryStream();
            if (width == _OriginalImage.Width && height == _OriginalImage.Height)
            {
                tempImage = (Bitmap)_OriginalImage.Clone();
            }
            else
            {
                tempImage = new Bitmap(width, height);
                Graphics graphics = Graphics.FromImage(tempImage);
                graphics.Clear(Color.White);
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                graphics.DrawImage(_OriginalImage,
                    new Rectangle(0, 0, tempImage.Width, tempImage.Height));
                graphics.Dispose();
            }
            SaveImage(oZonedStream, tempImage, personinfoid,extName);
            tempImage.Dispose();
            _OriginalImage.Dispose();
            return oZonedStream;
        }
        void SaveImage(Stream outStream, Image image, int personinfoid,string extName)
        {
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;

            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];
                    break;
                }
            }

            if (jpegICI != null)
            {
                image.Save(outStream, jpegICI, encoderParams);
            }
            else
            {
                image.Save(outStream, GetImageFormat(extName));
            }

        }

        static ImageFormat GetImageFormat(string extName)
        {
            if (extName.ToUpper().Equals(".GIF"))
                return ImageFormat.Gif;
            return ImageFormat.Jpeg;

        }
    }
}
